#!/bin/bash

# 部署脚本
echo "开始部署七牛云AI平台..."

# 1. 构建前端
echo "构建前端..."
cd front
npm install
npm run build
cd ..

# 2. 构建后端
echo "构建后端..."
cd backend
mvn clean package -DskipTests
cd ..

# 3. 创建部署目录
echo "创建部署目录..."
sudo mkdir -p /var/www/html
sudo mkdir -p /opt/qiniu-ai

# 4. 复制前端文件
echo "复制前端文件..."
sudo cp -r front/dist/* /var/www/html/

# 5. 复制后端文件
echo "复制后端文件..."
sudo cp backend/target/*.jar /opt/qiniu-ai/

# 6. 复制nginx配置
echo "配置nginx..."
sudo cp nginx.conf /etc/nginx/sites-available/qiniu-ai
sudo ln -sf /etc/nginx/sites-available/qiniu-ai /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

# 7. 创建systemd服务
echo "创建后端服务..."
sudo tee /etc/systemd/system/qiniu-ai.service > /dev/null <<EOF
[Unit]
Description=Qiniu AI Platform
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/qiniu-ai
ExecStart=/usr/bin/java -jar /opt/qiniu-ai/*.jar
Restart=always
RestartSec=10
Environment=SPRING_PROFILES_ACTIVE=prod

[Install]
WantedBy=multi-user.target
EOF

# 8. 启动服务
echo "启动服务..."
sudo systemctl daemon-reload
sudo systemctl enable qiniu-ai
sudo systemctl start qiniu-ai

# 9. 检查服务状态
echo "检查服务状态..."
sudo systemctl status qiniu-ai
sudo systemctl status nginx

echo "部署完成！"
echo "前端访问: http://your-domain.com"
echo "后端API: http://your-domain.com/api/"
echo "WebSocket: ws://your-domain.com/ws/"
